今天解釋一下昨天撰寫的程式碼
provider "google" {
project = var.project_id
region = var.region
}
# 創建一個 VPC 本體
resource "google_compute_network" "securenetwork" {
name = "securenetwork"
auto_create_subnetworks = "false"
}
# 在 VPC 內添加一個子網
resource "google_compute_subnetwork" "securenetwork" {
# 要先確認 VPC 被建立
depends_on = [google_compute_network.securenetwork]
name = "securenetwork"
region = var.region
network = google_compute_network.securenetwork.self_link
ip_cidr_range = "10.130.0.0/20"
}
# 創建一個 VPC 內的防火牆, 允許任意連線, 用 tcp:22 連到帶有特定 tag 的網內主機
resource "google_compute_firewall" "bastionbost-allow-iap" {
# 要確認 VPC 建立
depends_on = [google_compute_network.securenetwork]
name = "bastionbost-allow-iap"
network = google_compute_network.securenetwork.self_link
source_ranges = ["0.0.0.0/0"]
target_tags = ["bastion"]
allow {
protocol = "tcp"
ports = ["22"]
}
}
# 指定特定範圍內的主機連入內網任意電腦的網頁(port:80)
resource "google_compute_firewall" "securenetwork-allow-http" {
# 要確認 VPC 建立
depends_on = [google_compute_network.securenetwork]
name = "securenetwork-allow-http"
network = google_compute_network.securenetwork.self_link
source_ranges = ["10.130.0.0/20"]
allow {
protocol = "tcp"
ports = ["80"]
}
}
# 安全機(只能被特定內網 acccess)
resource "google_compute_instance" "safe_instance" {
# 建立到子網, 所以要確認子網已被建立
depends_on = [google_compute_subnetwork.securenetwork]
name = "secure"
zone = var.zone
machine_type = "e2-medium"
tags = ["secure"]
metadata = {
startup-script = "#! /bin/bash \n apt update \n apt -y install apache2 \n cat <<EOF > /var/www/html/index.html \n <html><body><p>Linux startup script added directly.</p></body></html> \n EOF"
}
boot_disk {
initialize_params {
image = "projects/debian-cloud/global/images/debian-11-bullseye-v20230814"
size = 20
type = "pd-balanced"
}
}
network_interface {
subnetwork = google_compute_subnetwork.securenetwork.self_link
access_config {
# Allocate a one-to-one NAT IP to the instance
}
}
}
# 堡壘機
resource "google_compute_instance" "bastion_instance" {
depends_on = [google_compute_network.securenetwork]
name = "bastion"
zone = var.zone
machine_type = "e2-micro"
# 利用 tag 適配防火牆規則
tags = ["bastion"]
boot_disk {
initialize_params {
image = "projects/debian-cloud/global/images/debian-11-bullseye-v20230814"
size = 20
type = "pd-balanced"
}
}
network_interface {
subnetwork = google_compute_network.securenetwork.self_link
access_config {
# Allocate a one-to-one NAT IP to the instance
}
}
}
curl http://<secure 內網 IP>
可以成功獲取測試網頁